package com.quzhi.sys.controller.UserController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quzhi.common.Result;
import com.quzhi.common.Utils;
import com.quzhi.sys.entity.Notice;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.service.impl.NoticeServiceImpl;
import com.quzhi.sys.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器 系統公告
 * </p>
 *
 * @author Xibing
 * @since 2024-08-19
 */
@RestController
@RequestMapping("/sys/notice")
public class NoticeController {

    @Autowired
    private NoticeServiceImpl noticeService;


    @Autowired
    private UserServiceImpl userService;


    /**
     * 获取所有公告
     */
    @GetMapping("/list")
    public Result<?> getNoticeList() {

        LambdaQueryWrapper<Notice> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Notice::getCreateTime);
        List<Notice> list = noticeService.list(lambdaQueryWrapper);

        return Result.success(list);
    }


    /**
     * 添加公告
     */
    @PostMapping
    public Result<?> addNotice(@RequestBody Notice notice, HttpServletRequest request) {
        notice.setId(UUID.randomUUID().toString());

        notice.setCreateTime(LocalDateTime.now());

        String token = Utils.getToken(request);

        User userinfoForBack = userService.getUserinfoForBack(token);

        notice.setOperator(userinfoForBack.getUsername());

        noticeService.save(notice);

        return Result.success("发布成功");
    }


    /**
     * 刪除公告
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteById(@PathVariable String id, HttpServletRequest request) {

        String token = Utils.getToken(request);
        User userinfoForBack = userService.getUserinfoForBack(token);

        if(userinfoForBack.getRole() == null)  return Result.success("你没有权限删除这条公告");
        if (userinfoForBack.getRole().equals("admin")) {
            noticeService.removeById(id);

            return Result.success("删除成功");
        } else {
            return Result.success("你没有权限删除这条公告");
        }

    }


}
